// pages/login-component/loginPage/loginPage.js
var MD5 = require("./helper/common/md5.js");
import Utils from "./helper/common/util.js"
import LoginApi from "./helper/network/loginApi.js";
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    systemName: {
      type: String,
    },
    systemID: {
      type: String,
    },
    appID: {
      type: String,
    },
    appSecret: {//此参数微信已不要求传
      type: String,
      value:''
    },
    isAfterUserLogout: {
      type: Boolean,
      value: false
    },
    phoneType: {
      type: Number,
      value:6
    },
    systemIconUrl: {
      type: String,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    showItemList:'none',
    schoolInfo: [],
    schoolName: null,
    account: null,
    password: null,
    userInfo: {},
    schoolSearchViewTop: 350,
    schoolSearchFocus: false,
    schoolItem: null,
    openID: null,
    unionID: null,
    icons:[require('./images/login-back.png'), require('./images/login-school-icon.png'), require('./images/login-user.png'), require('./images/login-password.png')],
    systemImageUrl : require('./images/login-logo.png')
  },
  lifetimes: {
    attached: function () { 
      // 在组件实例进入页面节点树时执行
      if (this.properties.isAfterUserLogout) {
        this.updateUnoinInfo();
        this.sendSchoolsInfoRequst();
        return;
      }else{
        this.sendSchoolsInfoRequst();
        this.getUnionIDStorage();
      }
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  pageLifetimes: {
    show: function () {
      // 页面被展示
      var that = this;
      wx.createSelectorQuery()
        .in(this)
        .select(".login-cell-school")
        .boundingClientRect(function (res) {
          that.setData({
            schoolSearchViewTop: res.top + res.height,
          });
        })
        .exec();
    },
    hide: function () {
      // 页面被隐藏
    },
    resize: function (size) {
      // 页面尺寸变化
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //检测学校是否可用
    checkCurSchoolState(){
      const { SchoolState } = this.data.schoolItem || {}//0：不可用，1：可用，2：维护中
      let result = { state:0, msg:'不可用' }
      switch (SchoolState) {
        case 0:
          result = { state:0, msg:'当前学校状态不可用' }
          break;
        case 1:
          result = { state:1, msg:'当前学校状态可用' }
          break;
        case 2:
          result = { state:2, msg:'当前学校状态维护中' }
          break;
        default:
          break;
      }
      return result
    },
    //当前学校缓存
    updateCurSchoolStorage(type = 0, shoolInfo){//0清空1更新/新建
      if(type === 0){//清空
        wx.removeStorage({key: 'curSchoolInfo'});
      }else{//更新
        wx.setStorage({
          key: 'curSchoolInfo',
          data: JSON.stringify(shoolInfo)
        });
      }
    },
    //①获取UnionID自动登录
    getUnionIDStorage: function () {
      console.log(
        "====================触发第一步getUnionIDStorage=========================="
      );
      var that = this;
      try {
        wx.getStorage({
          key: "unionID",
          success: function (res) {
            if (res.data) {
              console.log("缓存UnionID:", res.data);
              that.autoLoginWithUnionID(res.data);
            } else {
              that.getUserInfo();
            }
          },
          fail: function (res) {
            that.getUserInfo();
          },
        });
      } catch (e) {
        that.getUserInfo();
      }
    },

    //② 获取wx.login获取用户信息,自动登录
    getUserInfo: function (e) {
      console.log(
        "====================触发第二步getUserInfo=========================="
      );
      let that = this;
      wx.showLoading({
        title: "请稍后",
        mask: true,
      });
      // 微信登录
      wx.login({
        success: (res) => {
          console.log(res);
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          if (res.code) {
            that.autoLoginCheck(res);
          }
        },
        fail(res) {
          wx.hideLoading();
          wx.clearStorage({
            complete: (res) => {},
          });
          that.showGetUserInfoAgain("登录失败");
        },
      });
    },

    //③通过UnionID执行后台检测绑定API,获取到信息证明已绑定,直接登录
    autoLoginWithUnionID: function (unionID) {

     
      console.log(
        "====================触发第三步autoLoginWithUnionID wxLogin=========================="
      );

      //*********************>同步获取opendID<*********************
      try {
        let StorageOpenID = wx.getStorageSync("openID");
        if (StorageOpenID) {
          console.log("请求参数前拿到openID:", StorageOpenID);
          this.setData({
            openID: StorageOpenID,
          });
        } else {
          console.log("openID又丢失了，天！");
          that.getUserInfo();
        }
      } catch (e) {
        console.log(e);
      }
      // *********************>同步获取opendID结束<********************


      wx.showLoading({ title: "登录中...", mask: true });
      var that = this;

      var urlParam = {
        AppID: that.properties.appID,
        BrowserInfo: "Andriod",
        LoginIP: "192.168.2.90",
        MacAddress: " ",
        MachineType: that.properties.phoneType,
        SysTemID: that.properties.systemID,
        encryptedData: " ",
        WXName: " ",
        WXPhoto: " ",
        phone: "null",
        openID: that.data.openID,
        unionID: unionID,
      };

      LoginApi.wxLoginWithUnionIDApi(urlParam)
        .then((data) => {
          wx.hideLoading();
          console.log(data);
          if (data["error"] == 0) {
            switch (data.data["state"]) {
              case 0: //登录成功
                that.loginToMainPageWithData(data);
                break;
              case 1: //用户未绑定微信
                this.updateUnoinInfo();
                wx.showToast({
                  title: "请登录",
                  icon: "none",
                  duration: 2000,
                });
                break;
              case 2: //登录云平台失败
                wx.showToast({
                  title: "请求失败,请重新登录",
                  icon: "none",
                  duration: 2000,
                });
                break;
              case 3: //获取微信信息失败，一般是获取UinonID失败
                this.updateUnoinInfo();
                wx.showToast({
                  title: "获取微信信息失败，请重新登录",
                  icon: "none",
                  duration: 2000,
                });
                break;
              case 4: //找不到该学校id对应的学校
                wx.showToast({
                  title: "获取学校信息失败,请重新登录",
                  icon: "none",
                  duration: 2000,
                });
                break;
              case 5: //其他
                that.updateUnoinInfo();
                wx.showToast({
                  title: "获取用户信息,请重新登录",
                  icon: "none",
                  duration: 2000,
                });
                break;
              default:
                break;
            }
          } else {
            this.updateUnoinInfo();
            wx.showToast({
              title: "登录失败,请重新登录",
              icon: "none",
              duration: 2000,
            });
          }
        })
        .catch((e) => {
          wx.showToast({
            title: "请求失败,请重新登录",
            icon: "none",
            duration: 2000,
          });
          this.updateUnoinInfo();
        });
    },

    //④通过登录获取js_code 执行后台检测绑定API,获取到信息证明已绑定,直接登录
    autoLoginCheck: function (res) {
      console.log(
        "====================触发第四步autoLoginCheck wxlogin=========================="
      );
      var that = this;
      var urlParam = {
        AppID: that.properties.appID,
        BrowserInfo: "Andriod",
        LoginIP: "192.168.2.90",
        MacAddress: " ",
        MachineType: that.properties.phoneType,
        Secret: that.properties.appSecret,
        SysTemID: this.properties.systemID,
        js_Code: res.code,
        encryptedData: " ",
        iv: " ",
        WXName: " ",
        WXPhoto: " ",
        phone: "null",
      };
      // 自动登陆获取unionID和openID，得到数据后将unionID和openID进行缓存
      LoginApi.wxLoginApi(urlParam)
        .then((data) => {
          console.log(data);
          wx.hideLoading();
          if (data["error"] == 0) {
            switch (data.data["state"]) {
              case 0: //登录成功
                // that.setStorageSyncUnionIDandOpenID(data);
                that.loginToMainPageWithData(data);
                break;
              case 1: //用户未绑定微信
                that.updateUnoinInfo();
                wx.setStorageSync("unionID", data.data.wxsession.unionid);
                wx.setStorageSync("openID", data.data.wxsession.openid);
                wx.showToast({
                  title: "请登录",
                  icon: "none",
                  duration: 2000,
                });
                break;
              case 2: //登录云平台失败
                wx.setStorageSync("unionID", data.data.wxsession.unionid);
                wx.setStorageSync("openID", data.data.wxsession.openid);
                wx.showToast({
                  title: "请求失败,请重新登录",
                  icon: "none",
                  duration: 2000,
                });
                break;
              case 3: //获取微信信息失败，一般是获取UinonID失败
                this.updateUnoinInfo();
                wx.showToast({
                  title: "获取微信信息失败，请重新登录",
                  icon: "none",
                  duration: 2000,
                });
                break;
              case 4: //找不到该学校id对应的学校
                wx.setStorageSync("unionID", data.data.wxsession.unionid);
                wx.setStorageSync("openID", data.data.wxsession.openid);
                wx.showToast({
                  title: "获取学校信息失败,请重新登录",
                  icon: "none",
                  duration: 2000,
                });
                break;
              case 5: //其他
                this.updateUnoinInfo();
                wx.showToast({
                  title: "获取用户信息,请重新登录",
                  icon: "none",
                  duration: 2000,
                });
                break;
              default:
                break;
            }
          } else {
            this.updateUnoinInfo();
            wx.showToast({
              title: "登录失败,请重新登录",
              icon: "none",
              duration: 2000,
            });
          }
        })
        .catch((e) => {
          wx.showToast({
            title: "请求失败,请重新登录",
            icon: "none",
            duration: 2000,
          });
          this.updateUnoinInfo();
        });
    },
    // 将unionID和openID进行缓存
    setStorageSyncUnionIDandOpenID(data) {
      console.log(
        "------------> 自动登陆异步缓存unionID和openID <------------"
      );
      wx.setStorageSync("unionID", data.data.wxsession.unionid);
      wx.setStorageSync("openID", data.data.wxsession.openid);
    },
    //⑤手动登录
    loginAction: function () {

      console.log(
        "====================手动登陆loginAction yunLoginApi=========================="
      );

      var that = this;
      if (!that.data.openID || !that.data.unionID) {
        wx.showToast({
          title: "获取用户信息失败,请稍后重试",
          icon: "none",
          duration: 2000,
        });
        this.updateUnoinInfo();
        return;
      }

      if (!this.data.schoolItem) {
        wx.showToast({
          title: "请确保选择正确学校",
          icon: "none",
          duration: 2000,
        });
        return;
      }else{//可进入的学校
        const curSchoolInfo = this.checkCurSchoolState()
        if(curSchoolInfo.state != 1){
          wx.showToast({
          title: curSchoolInfo.msg,
          icon: "none",
          duration: 2000,
        });
          return
        }
      }

      if (!this.data.account) {
        wx.showToast({
          title: "请输入账号",
          icon: "none",
          duration: 2000,
        });
        return;
      }

      if (!this.data.password) {
        wx.showToast({
          title: "请输入密码",
          icon: "none",
          duration: 2000,
        });
        return;
      }

      wx.showLoading({
        title: "登录中...",
        mask: true,
      });
      var urlParam = {
        AppID: that.properties.appID,
        BrowserInfo: "Andriod",
        LoginIP: "192.168.2.90",
        MacAddress: "",
        MachineType: that.properties.phoneType,
        OpenID: that.data.openID,
        PSW: MD5.reverseMD5String(this.data.password),
        SchoolID: this.data.schoolItem.SchoolID,
        SysTemID: this.properties.systemID,
        UnionID: that.data.unionID,
        UserID: this.data.account,
        WXName: "",
        WXPhoto: "",
        phone: "null",
      };

      LoginApi.yunLoginApi(urlParam)
        .then((data) => {
          var that = this;
          wx.hideLoading();
          if (data["error"] == 0) {
            if (data.data["userInfo"]) {
              that.updateCurSchoolStorage(1, this.data.schoolItem)
              that.loginToMainPageWithData(data);
            } else if (data.data["msg"] == "账号密码不匹配") {
              wx.showToast({
                title: "账号密码不匹配,请重新输入",
                icon: "none",
                duration: 2000,
              });
            } else {
              wx.showToast({
                title: data.data["msg"],
                icon: "none",
                duration: 2000,
              });
            }
          } else {
            wx.showToast({
              title: "登录失败,请稍后再试",
              icon: "none",
              duration: 2000,
            });
          }
        })
        .catch((e) => {
          wx.showToast({
            title: "请求失败",
            icon: "none",
            duration: 2000,
          });
          console.error("请求失败", e);
        });
    },

    //获取学校信息
    sendSchoolsInfoRequst: function () {
      var that = this;
      //先获取学校缓存，再更新学校缓存
      wx.getStorage({
        key: "schoolsInfo",
        success: function (res) {
          var schoolsInfoArr = JSON.parse(res.data);
          that.setData({
            schoolInfo: schoolsInfoArr,
          });
        },
      });
      wx.getStorage({
        key: 'curSchoolInfo',
        success: (result)=>{
          console.log(result)
          const schoolItem = JSON.parse(result.data)
          , { SchoolName } = schoolItem
          this.data.schoolItem = schoolItem
          that.setData({ 
            schoolName:SchoolName
          })
        }
      });
      LoginApi.getSchoolApi()
        .then((data) => {
          if (data["error"] == 0) {
            //缓存学校信息
            var schoolsInfo = JSON.stringify(data.data);
            wx.setStorage({
              key: "schoolsInfo",
              data: schoolsInfo,
            });
            that.setData({
              schoolInfo: data.data,
            });
          } else {
            wx.getStorage({
              key: "schoolsInfo",
              success: function (res) {
                var schoolsInfoArr = JSON.parse(res.data);
                that.setData({
                  schoolInfo: schoolsInfoArr,
                });
              },
            });
          }
        })
        .catch((e) => {});
    },

    //更新Union信息
    updateUnoinInfo: function () {

      console.log(
        "====================更新updateUnoinInfo getUnionIdApi=========================="
      );

      var that = this;
      wx.getStorage({
        key: "openID",
        success: function (res) {
          if (res.data) {
            that.setData({
              openID: res.data,
            });
          }
        },
      });
      wx.getStorage({
        key: "unionID",
        success: function (res) {
          if (res.data) {
            that.setData({
              unionID: res.data,
            });
          }
        },
      });

      wx.login({
        success: (res) => {
          if (res.code) {
            this.getUnionIDInfoRequest(res.code);
          }
        },
      });
    },

    //获取UnionID
    getUnionIDInfoRequest: function (code) {
      var that = this;
      console.log(code);
      var param = {
        AppID: that.properties.appID,
        js_Code: code,
        Secret: that.properties.appSecret,
        encryptedData: " ",
        iv: " ",
      };
      LoginApi.getUnionIdApi(param).then((result) => {
        const { error, msg, data } = result;
        console.log("----", data);
        if (error == 0) {
          that.setData({
            openID: data.openid,
            unionID: data.unionid,
          });
          that.stroageUnionIDAndOpenID(data.unionid, data.openid);
        }
      });
    },

    //缓存UnionID
    stroageUnionIDAndOpenID: function (unionID, openID) {
      console.log("对最新的openID和openID进行本地存储");
      wx.setStorageSync("openID", openID);
      wx.setStorageSync("unionID", unionID);
    },

    //获取数据成功，登录到对应页面
    loginToMainPageWithData: function (data) {
      this.triggerEvent("loginSucceed", data);
    },

    //跳转到对应界面
    redirectToRolePage: function (data) {
      var that = this;
      wx.showToast({
        title: "登录成功",
        icon: "success",
        duration: 1000,
      });
      this.loginSucceed(data);
    },

    //学校选择输入框相关事件===============================
    filterSchoolInfo(searchName){
      if(!searchName)return
      var searchSchoolArr = this.data.schoolInfo.filter(o=>{
        return o.SchoolName.indexOf(searchName) != -1
      });
      this.setData({
        searchSchoolArr: searchSchoolArr,
        schoolItem: null,
      });
    },
    schoolFocusAction: function () {
      this.filterSchoolInfo(this.data.schoolName)
      this.setData({
        schoolSearchFocus: true,
        showItemList:'block'
      });
    },
    schoolBlurAction: function (sender) {
      if(!this.data.isSelect){
        console.log(sender.detail.value);
        this.setData({
          schoolSearchFocus: false,
          searchSchoolArr: [],
          showItemList:'none'
        });
  
        if (!this.data.schoolItem) {
          this.data.schoolInfo.forEach((element) => {
            if (element.SchoolName == sender.detail.value) {
              this.setData({
                schoolItem: element,
              });
            }
          });
        }
      }
    },
    
    handMouseDownSearch(e){
      this.data.isSelect = true
    },
    handSearchSchoolItem: function (sender) {
      this.setData({
        schoolName: sender.currentTarget.dataset.item.SchoolName,
        schoolItem: sender.currentTarget.dataset.item,
        schoolSearchFocus: false,
        searchSchoolArr: [],
      });
      this.data.isSelect = false
    },

    schoolInput: function (sender) {
      this.filterSchoolInfo(sender.detail.value)
    },
    //学校选择输入框相关事件==============================结束

    //账号输入
    accountAction: function (sender) {
      this.setData({
        account: sender.detail.value,
      });
    },

    //密码输入
    passwordAction: function (sender) {
      this.setData({
        password: sender.detail.value,
      });
    },

    //获取用户信息失败,重新获取用户信息
    showGetUserInfoAgain: function (e) {
      var that = this;
      wx.showModal({
        title: "提示！",
        confirmText: "重新登录",
        showCancel: true,
        content: e,
        success: function (res) {
          if (res.confirm) {
            that.getUserInfo();
          }
        },
      });
    },
  },
});
